Python | 您所在的位置:网站首页 › python字符串去掉/n › Python |
正则表达式是一个很好的、非常通用的工具,适用于各种字符串的分析。如果速度是一个问题,来自字符串类的 "翻译 "方法也可以帮助你。 首先,你定义一个('身份')映射,这不会改变任何东西。 mapping = map(chr, range(256))如果你想用一个 "b "来代替每个 "a",你要修改你的映射关系 mapping[ord('a')] = 'b'现在你为 "翻译 "方法建立表格。 table = "".join(mapping)和 print "abc".translate(table)prints "bbc". If you really want to delete the "a", you do not modify the mapping above, build the table 和 then call translate as follows: print "abc".translate(table, "a")gives you "bc". 一旦建好了表,翻译方法就非常快。 因此,在你的情况下,你可以修改映射,使你所有不需要的字符都被映射到一个空白处。 mapping = map(chr, range(256)) table = "".join( " " if c in unwanted_chars else c for c in map(chr, range(256)) )和 use len("my string".translate(table).trim()) which ignores the unwanted characters at the beginning 和 the end of the string. 或者你使用len("my string".translate(table, unwanted_chars)),它将忽略所有你不需要的字符。 |
CopyRight 2018-2019 实验室设备网 版权所有 |